package com.qf.flash.ui.home;

import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.androidkun.xtablayout.XTabLayout;
import com.qf.dblib.dao.entity.SearchHistoryBean;
import com.qf.dblib.dao.impl.SearchHistoryDao;
import com.qf.dblib.dao.impl.UserMgr;
import com.qf.flash.R;
import com.qf.flash.http.HttpManager;
import com.qf.flash.http.response.PlayConditinoResponse;
import com.qf.flash.model.GameGroupBean;
import com.qf.flash.model.ScriptRoomBean;
import com.qf.flash.mvp.contract.ScriptContract;
import com.qf.flash.mvp.presenter.ScriptPrensenter;
import com.qf.flash.ui.home.adapter.GameGroupItem2;
import com.qf.flash.ui.home.adapter.ScriptItem;
import com.qf.flashlib.adapter.RVAdapter;
import com.qf.flashlib.base.BaseActivity;
import com.qf.flashlib.base.BaseResponse;
import com.qf.flashlib.base.BaseSubscriber;
import com.qf.flashlib.exception.ApiException;
import com.qf.flashlib.util.RxUtils;
import com.qf.flashlib.widget.ViewUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * 创建日期：2020/2/24 on 21:20
 * 描述:  首页的搜索页面
 * 作者:戴旭东
 */
public class HomeSearchActivity extends BaseActivity implements ScriptContract.View {
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.tfl_history)
    TagFlowLayout tflHistory;
    @BindView(R.id.tabLayout)
    XTabLayout tabLayout;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.ll_history)
    LinearLayout llHistory;
    @BindView(R.id.ll_data)
    LinearLayout llData;
    @BindView(R.id.mRefresh)
    SmartRefreshLayout mRefresh;

    private RVAdapter<Object> mAdapter;
    private ScriptPrensenter mScriptPresenter;
    private int pageNo = 1;
    private boolean isRefresh;
    private Disposable disposable;

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, HomeSearchActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void initInject() {
        mScriptPresenter = new ScriptPrensenter();
        initPresenters(mScriptPresenter);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_home_search;
    }

    @Override
    protected void initViewAndData() {
        initTab();
        initSearchHistory();
        initRecyclerView();
        initRefresh();
        etContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    startSearch();
                }
                return false;
            }
        });

    }

    private void initRefresh() {
        mRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNo++;
                isRefresh = false;
                requestData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNo = 1;
                isRefresh = true;
                requestData();

            }
        });
    }


    private void initTab() {
        tabLayout.addTab((tabLayout.newTab().setText("队伍")));
        tabLayout.addTab((tabLayout.newTab().setText("剧本/主题")));
        tabLayout.setOnTabSelectedListener(new XTabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(XTabLayout.Tab tab) {
                mRefresh.autoRefresh();
            }

            @Override
            public void onTabUnselected(XTabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(XTabLayout.Tab tab) {

            }
        });
    }

    private void requestData() {
        if (tabLayout.getSelectedTabPosition() == 0) {
            getGameListByName(etContent.getText().toString(), pageNo);
        } else {
            getPlayListHotData();
        }
    }

    private void getPlayListHotData() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", etContent.getText().toString());
        map.put("pageNo", pageNo);
        mScriptPresenter.getPlayList(map);
    }

    public void getGameListByName(String name, int page) {
        String uid = UserMgr.getInstance().getLoginUser().getUid();
        disposable = HttpManager.getInstance().getGsonHttpApi()
                .GAME_SEARCH(uid, name, page)
                .compose(RxUtils.handleBaseResult())
                .compose(RxUtils.io_main())
                .subscribeWith(new BaseSubscriber<BaseResponse<List<GameGroupBean>>>(
                        this, false) {
                    @Override
                    public void onSuccess(BaseResponse<List<GameGroupBean>> game) {
                        setGameList(game.getData(), game.getTotalPage());
                    }
                });
    }

    private void setGameList(List<GameGroupBean> data, int totalPage) {
        if (isRefresh) {
            mAdapter.setDatas(new ArrayList<>(data));
        } else {
            mAdapter.addData(new ArrayList<>(data));
        }
        ViewUtil.setRefreshComplete(mRefresh, isRefresh);
        mRefresh.setEnableLoadMore(pageNo < totalPage);
    }

    private void initRecyclerView() {
        mAdapter = new RVAdapter<>(new GameGroupItem2(), new ScriptItem(this));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemChildClickListener(new RVAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(View view, int position) {
                Object data = mAdapter.getData(position);
                if (data instanceof GameGroupBean) {
                    GameGroupBean bean = (GameGroupBean) data;
                    GroupDetailActivity.start(HomeSearchActivity.this, bean.getId(), bean.getPlayId());
                }
            }
        });
        mAdapter.setOnItemClickListener(new RVAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Object data = mAdapter.getData(position);
                if (data instanceof ScriptRoomBean) {
                    ScriptDetailActivity.start(HomeSearchActivity.this, ((ScriptRoomBean) data).getId());
                }
            }
        });
    }

    private void startSearch() {
        llData.setVisibility(View.VISIBLE);
        llHistory.setVisibility(View.GONE);
        if (!TextUtils.isEmpty(etContent.getText().toString()))
            SearchHistoryDao.getInstance().saveHistory(etContent.getText().toString());
        mRefresh.autoRefresh();
    }


    @OnClick({R.id.fl_back, R.id.tv_top_right, R.id.iv_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.fl_back:
            case R.id.tv_top_right:
                finish();
                break;
            case R.id.iv_delete:
                SearchHistoryDao.getInstance().clearAllData();
                initSearchHistory();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
            disposable = null;
        }
    }

    /**
     * 初始化搜索历史
     */
    private void initSearchHistory() {
        final List<SearchHistoryBean> searchHistoryBeans = SearchHistoryDao.getInstance().queryHistroy();
        tflHistory.setAdapter(new TagAdapter<SearchHistoryBean>(searchHistoryBeans) {
            @Override
            public View getView(FlowLayout parent, int position, SearchHistoryBean s) {
                TextView tv_hot = (TextView) LayoutInflater.from(HomeSearchActivity.this).inflate(R.layout.item_history, tflHistory, false);
                tv_hot.setText(s.getValue());
                return tv_hot;
            }
        });
        tflHistory.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                etContent.setText(searchHistoryBeans.get(position).getValue());
                //保存记录
                startSearch();
                return true;
            }
        });
    }


    @Override
    public void setPlayListData(List<ScriptRoomBean> data, int totalPage) {
        if (isRefresh) {
            mAdapter.getDatas().clear();
        }
        mAdapter.getDatas().addAll(data);
        mAdapter.notifyDataSetChanged();
        ViewUtil.setRefreshComplete(mRefresh, isRefresh);
        mRefresh.setEnableLoadMore(pageNo < totalPage);
    }

    @Override
    public void onError(ApiException e) {
        super.onError(e);
        ViewUtil.setRefreshComplete(mRefresh, isRefresh);
    }

    @Override
    public void setConditionData(PlayConditinoResponse response) {

    }
}
